package com.guli.produce.produce.service.impl;

import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.guli.produce.produce.dao.CategoryDao;
import com.guli.produce.produce.entity.CategoryEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guli.common.utils.PageUtils;
import com.guli.common.utils.Query;

import com.guli.produce.produce.dao.AttrGroupDao;
import com.guli.produce.produce.entity.AttrGroupEntity;
import com.guli.produce.produce.service.AttrGroupService;


@Service("attrGroupService")
public class AttrGroupServiceImpl extends ServiceImpl<AttrGroupDao, AttrGroupEntity> implements AttrGroupService {
    @SuppressWarnings("all")
    @Autowired
    private CategoryDao categoryDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params,Long catelogId) {
        QueryWrapper<AttrGroupEntity> w = new QueryWrapper<>();
        if (!catelogId.equals(0l)){
            w.eq("catelog_id",catelogId);
        }
        IPage<AttrGroupEntity> page = this.page(
                new Query<AttrGroupEntity>().getPage(params),
              w
        );

        return new PageUtils(page);
    }



    //做回显

    @Override
    public AttrGroupEntity getById(Serializable id) {
        //首先根据id去查询到当前数据
        AttrGroupEntity attrGroupEntity = baseMapper.selectById(id);

        //创建一个集合来接收
        List<Long> list=new ArrayList<>();

        //根据是否fid为0去判断是否有上一级
        Long catelogId = attrGroupEntity.getCatelogId();


        //调用方法
        path(list,catelogId);
        //将集合中的元素进行反转   1,2,3--->3,2,1
        Collections.reverse(list);
        //将集合转成数组
        Long[] ids =  list.toArray(new Long[list.size()]);
        //将转成的数组存入对应的字段中
        attrGroupEntity.setCatelogPath(ids);
        //list
        return attrGroupEntity;
    }

    //创建递归方法
    public void path(List<Long> list, Long catelogId){
        //先把最后一级存入集合中
        list.add(catelogId);
        //根据最后一级去查询上级
        CategoryEntity categoryEntity = categoryDao.selectById(catelogId);
        //判断fid不能为0
        if (!categoryEntity.getParentCid().equals(0l)){

            //自己调用自己
            path(list,categoryEntity.getParentCid());
        }

    }
}